package com.usian.day08.tag.controller;

import com.usian.common.model.day08.Tag;
import com.usian.common.vo.ResultResopnse;
import com.usian.day08.tag.service.TagCategoryService;
import com.usian.day08.tag.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author baimugudu
 * @email 2415621370@qq.com
 * @date 2023/8/4 14:15
 */
@RestController
@RequestMapping("/tag")
@Slf4j
public class TagController {
   @Autowired
   TagCategoryService tagCategoryService;

   @Autowired
   TagService tagService;


   @Autowired
   RedisTemplate redisTemplate;

   @PostMapping("/save")
   public ResultResopnse save(@RequestBody Tag tag){
       //保存到mysql
       try{
           boolean b = tagService.save(tag);
           redisTemplate.delete("tagList");
           return ResultResopnse.success(b);
       }catch (Exception e){
           e.printStackTrace();
           return ResultResopnse.error();
       }

   }

  @GetMapping("/list")
   public ResultResopnse list(){
       log.info("开始查询");
       //先从redis里面查询
      //如果有的话，直接返回
      //如果没有的话， 去mysql查询。然后保存到redis，在返回
      try{
          BoundListOperations boundListOperations = redisTemplate.boundListOps("tagList");
          List list = boundListOperations.range(0, -1);
          if(null!=list &&!list.isEmpty()){
              log.info("有的话，直接返回");
              return ResultResopnse.success(list);
          }else {
              log.info("没有的话， 去mysql查询。然后保存到redis，在返回");
              List<Tag> list1 = tagService.list();
              list1.forEach(i->{
                  redisTemplate.boundListOps("tagList").leftPush(i);

              });
              return ResultResopnse.success(list1);
          }
      }catch (Exception e){
          e.printStackTrace();
          return ResultResopnse.error();
      }




  }

}


